package com.hanyi.system.okhttp;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import okhttp3.*;
import java.io.File;
import java.util.Map;


/**
 * @author grantfee.li
 * @date 2023-10-09
 */
@Slf4j
@Component
public class OkHttpApi {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
    @Autowired
    private OkHttpClient okHttpClient;

    /**
     * get 请求
     * @param url       请求url地址
     * @return string
     * */
    public String doGet(String url) {
        return doGet(url, null, null);
    }


    /**
     * get 请求
     * @param url       请求url地址
     * @param params    请求参数 map
     * @return string
     * */
    public String doGet(String url, Map<String, Object> params) {
        return doGet(url, params, null);
    }

    /**
     * get 请求
     * @param url       请求url地址
     * @param headers   请求头字段 {k1, v1 k2, v2, ...}
     * @return string
     * */
    public String doGet(String url, String[] headers) {
        return doGet(url, null, headers);
    }


    /**
     * get 请求
     * @param url       请求url地址
     * @param params    请求参数 map
     * @param headers   请求头字段 {k1, v1 k2, v2, ...}
     * @return string
     * */
    public String doGet(String url, Map<String, Object> params, String[] headers) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && params.keySet().size() > 0) {
            boolean firstFlag = true;
            for (String key : params.keySet()) {
                if (firstFlag) {
                    sb.append("?").append(key).append("=").append((String)params.get(key));
                    firstFlag = false;
                } else {
                    sb.append("&").append(key).append("=").append((String)params.get(key));
                }
            }
        }

        Request.Builder builder = new Request.Builder();
        if (headers != null && headers.length > 0) {
            if (headers.length % 2 == 0) {
                for (int i = 0; i < headers.length; i = i + 2) {
                    builder.addHeader(headers[i], headers[i + 1]);
                }
            } else {
                log.warn("headers's length[{}] is error.", headers.length);
            }

        }

        Request request = builder.url(sb.toString()).build();
        log.error("do get request and url {}", sb.toString());
        String result = execute(request);
        log.error("response: {}", result);

        return result;
    }

    /**
     * post 请求
     * @param url       请求url地址
     * @param params    请求参数 map
     * @return string
     */
    public String doPost(String url, Map<String, Object> params) {
        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, (String)params.get(key));
            }
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        log.info("do post request and url[{}]", url);
        String result = execute(request);
        log.info("response: {}", result);
        return result;
    }


    /**
     * post 请求, 请求数据为 json 的字符串
     * @param url       请求url地址
     * @param json      请求数据, json 字符串
     * @return string
     */
    public String doPostJson(String url, String json,Map<String,String> headers) {
        log.info("do post request and url[{}]", url);
        return exectePost(url, json, JSON,headers);
    }



    /**
     * post 请求, 请求数据为 xml 的字符串
     * @param url       请求url地址
     * @param xml       请求数据, xml 字符串
     * @return string
     */
    public String doPostXml(String url, String xml) {
        log.info("do post request and url[{}]", url);
        return exectePost(url, xml, XML,null);
    }


    private String exectePost(String url, String data, MediaType contentType,Map<String,String> headers ) {
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request.Builder builder =  new Request.Builder();
        builder.url(url);
        if(headers!=null){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String name = entry.getKey();
                String value = entry.getValue();
                builder.addHeader(name,value);
            }
        }

        Request request = builder.post(requestBody).build();
//        Request request = new Request.Builder().url(url)
//                .addHeader("Authorization","APPCODE ")
//                .post(requestBody)
//                .build();
        log.info("request url:{}",url);
        String result = execute(request);
        log.info("response: {}", result);
        return result;
    }

    private String execute(Request request) {
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    public String downloadFile(Request request){
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                byte[] bytes = response.body().bytes();
                String result = Base64.encode(bytes);
                return result;
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * post 上传文件
     *
     * @param url
     * @param params
     * @return
     */
    public String uploadMultiFile(String url, Map<String, Object> params) {
        String responseBody = "";
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MediaType.parse("multipart/form-data"));
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                if (key.equals("avatarFile")) {
                    File file = new File((String)params.get(key)) ;
                    log.info(key+" add file part {}",(String)params.get(key));
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("image/jpeg"),file));
                }else{
                    if(params.get(key)!=null){
                        log.info(key+"  param:{}",params.get(key));
                        builder.addFormDataPart(key,params.get(key).toString());
                    }
                }
            }
        }
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (status == 200) {
                String result = response.body().string();
                //log.info("upload file response:{}",result);
                return result;
            }else{
                log.error("failed to upload,code:{},msg:{}",status,response.body().string());
            }
        } catch (Exception e) {
            log.error("okhttp postFile error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }


    /**
     * @param url
     * @param filePath
     * @param params
     * @return
     */
    public String uploadFile(String url,  String filePath, Map<String, Object> params )   {
        File file = new File(filePath);
        String fileName = file.getName();
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file",
                        fileName, fileBody)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        try{
            Response response = okHttpClient.newCall(request).execute();
            if (!response.isSuccessful()){
                return "";
            }
            return response.body().string();
        }catch (Exception e){
            e.printStackTrace();
        }

        return "";
    }

}
